﻿@page "/Account/ConfirmEmailChange"

@using System.Text
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.WebUtilities
@using MyApp.Data
@using MyApp.Identity

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject UserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager

<PageTitle>Confirm email change</PageTitle>

<Heading1>Confirm email change</Heading1>

<div class="mt-8 mx-auto max-w-lg">
    <StatusMessage Message="@_message" />
</div>

@code {
    private string? _message;
    private ApplicationUser _user = default!;

    [SupplyParameterFromQuery]
    private string? UserId { get; set; }

    [SupplyParameterFromQuery]
    private string? Email { get; set; }

    [SupplyParameterFromQuery]
    private string? Code { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (UserId is null || Email is null || Code is null)
        {
            RedirectManager.RedirectToWithStatus(
                "/Account/Login", "Error: Invalid email change confirmation link.");
            return;
        }

        _user = await UserAccessor.GetRequiredUserAsync();

        var code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Code));
        var result = await UserManager.ChangeEmailAsync(_user, Email, code);
        if (!result.Succeeded)
        {
            _message = "Error changing email.";
            return;
        }

        // In our UI email and user name are one and the same, so when we update the email
        // we need to update the user name.
        var setUserNameResult = await UserManager.SetUserNameAsync(_user, Email);
        if (!setUserNameResult.Succeeded)
        {
            _message = "Error changing user name.";
            return;
        }

        await SignInManager.RefreshSignInAsync(_user);
        _message = "Thank you for confirming your email change.";
    }
}
